<template>
  <div class="dashboard">
    <div class="page-header">
      <h2>系统仪表盘</h2>
      <el-button type="primary" @click="refreshData">
        <el-icon><Refresh /></el-icon>刷新数据
      </el-button>
    </div>

    <!-- 资源统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>集群总数</span>
              <el-icon><Connection /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ stats.totalClusters }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>节点总数</span>
              <el-icon><Monitor /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ stats.totalNodes }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>实例总数</span>
              <el-icon><Cpu /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ stats.totalInstances }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>资源使用率</span>
              <el-icon><DataLine /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ stats.resourceUsage }}%</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态图表 -->
    <el-row :gutter="20" class="charts">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>资源使用趋势</span>
            </div>
          </template>
          <div ref="resourceChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>系统负载分布</span>
            </div>
          </template>
          <div ref="loadChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-card class="recent-activities">
      <template #header>
        <div class="card-header">
          <span>最近活动</span>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="activity.timestamp"
          :type="activity.type"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Refresh, Connection, Monitor, Cpu, DataLine } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useCloudStore } from '../stores/cloud'

const store = useCloudStore()
const resourceChartRef = ref(null)
const loadChartRef = ref(null)
let resourceChart = null
let loadChart = null
let refreshTimer = null

const stats = ref({
  totalClusters: 0,
  totalNodes: 0,
  totalInstances: 0,
  resourceUsage: 0
})

const recentActivities = ref([])

onMounted(async () => {
  await Promise.all([fetchStats(), fetchRecentActivities()])
  initCharts()
  // 设置定时刷新
  refreshTimer = setInterval(refreshData, 30000) // 每30秒刷新一次
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  if (resourceChart) {
    resourceChart.dispose()
  }
  if (loadChart) {
    loadChart.dispose()
  }
})

async function fetchStats() {
  try {
    await store.fetchStats()
    stats.value = store.stats
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

async function fetchRecentActivities() {
  try {
    await store.fetchRecentActivities()
    recentActivities.value = store.recentActivities
  } catch (error) {
    ElMessage.error('获取最近活动失败')
  }
}

function initCharts() {
  // 初始化资源使用趋势图表
  resourceChart = echarts.init(resourceChartRef.value)
  const resourceOption = {
    title: {
      text: '资源使用趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['CPU使用率', '内存使用率', '磁盘使用率']
    },
    xAxis: {
      type: 'time',
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'line',
        data: store.resourceUsage.map(item => [item.timestamp, item.cpu_usage])
      },
      {
        name: '内存使用率',
        type: 'line',
        data: store.resourceUsage.map(item => [item.timestamp, item.memory_usage])
      },
      {
        name: '磁盘使用率',
        type: 'line',
        data: store.resourceUsage.map(item => [item.timestamp, item.disk_usage])
      }
    ]
  }
  resourceChart.setOption(resourceOption)

  // 初始化系统负载分布图表
  loadChart = echarts.init(loadChartRef.value)
  const loadOption = {
    title: {
      text: '系统负载分布'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '负载分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: store.loadDistribution.normal, name: '正常' },
          { value: store.loadDistribution.warning, name: '警告' },
          { value: store.loadDistribution.critical, name: '严重' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  loadChart.setOption(loadOption)
}

async function refreshData() {
  await Promise.all([fetchStats(), fetchRecentActivities()])
  if (resourceChart && loadChart) {
    resourceChart.setOption({
      series: [
        {
          data: store.resourceUsage.map(item => [item.timestamp, item.cpu_usage])
        },
        {
          data: store.resourceUsage.map(item => [item.timestamp, item.memory_usage])
        },
        {
          data: store.resourceUsage.map(item => [item.timestamp, item.disk_usage])
        }
      ]
    })
    loadChart.setOption({
      series: [{
        data: [
          { value: store.loadDistribution.normal, name: '正常' },
          { value: store.loadDistribution.warning, name: '警告' },
          { value: store.loadDistribution.critical, name: '严重' }
        ]
      }]
    })
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.stat-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
}

.charts {
  margin-bottom: 20px;
}

.recent-activities {
  margin-bottom: 20px;
}
</style> 